<?php

namespace common\widgets\markdown;

use Yii;
use Closure;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\helpers\MenuHelper;
use cebe\markdown\GithubMarkdown;

/**
 * LeftMenu displays a multi-level menu using nested HTML lists.
 *
 * ```php
 * echo LeftMenu::widget([
 *     'options' => [
 *          'class' => 'page-sidebar-menu page-sidebar-menu-light',
 *          'data-keep-expanded' => false,
 *          'data-auto-scroll' => true,
 *          'data-slide-speed' => 100,
 *     ]
 * ]);
 * ```
 *
 * @author emhome<emhome@163.com>
 * @since 1.0
 */
class MarkdownParser extends \yii\base\Widget {

    public $body = null;

    /**
     * @var array the HTML attributes for the menu's container tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = [
        'class' => 'md-box'
    ];

    /**
     * Renders the menu.
     */
    public function run() {
        if ($this->body === null) {
            return;
        }
        $view = $this->getView();
        MarkdownAsset::register($view);
        $js = 'hljs.initHighlightingOnLoad();';
        $view->registerJs($js, \yii\web\View::POS_END);
        $content = $this->renderMarkdown($this->body);

        $tag = ArrayHelper::remove($this->options, 'tag', 'div');
        return Html::tag($tag, $content, $this->options);
    }

    /**
     * Renders the markdown.
     */
    protected function renderMarkdown($content) {
        $parser = new GithubMarkdown();
        return $parser->parse($content);
    }

}
